#include "net.hpp"
#include <iostream>
#include <thread>
#include <chrono>

using namespace jsonrpc;

// 处理服务器响应的回调函数
void onServerMessage(const BaseConnection::ptr& conn, BaseMessage::ptr& msg) {
    switch (msg->getMessageType()) {
        case MType::RSP_RPC: {
            auto rsp = std::dynamic_pointer_cast<RpcResponse>(msg);
            if (rsp) {
                LOG_INFO("Received RPC response: rcode=%d, result=%s", 
                        static_cast<int>(rsp->getRCode()),
                        rsp->getResult().toStyledString().c_str());
            }
            break;
        }
        case MType::RSP_TOPIC: {
            auto rsp = std::dynamic_pointer_cast<TopicResponse>(msg);
            if (rsp) {
                LOG_INFO("Received Topic response: rcode=%d", 
                        static_cast<int>(rsp->getRCode()));
            }
            break;
        }
        case MType::RSP_SERVICE: {
            auto rsp = std::dynamic_pointer_cast<ServiceResponse>(msg);
            if (rsp) {
                LOG_INFO("Received Service response: rcode=%d, optype=%d", 
                        static_cast<int>(rsp->getRCode()),
                        static_cast<int>(rsp->getOptype()));
                
                if (rsp->getOptype() == ServiceOptype::SERVICE_DISCOVERY) {
                    auto hosts = rsp->hosts();
                    LOG_INFO("Discovered %zu services:", hosts.size());
                    for (const auto& host : hosts) {
                        LOG_INFO("  %s:%d", host.first.c_str(), host.second);
                    }
                }
            }
            break;
        }
        default:
            LOG_ERROR("Unknown message type: %d", static_cast<int>(msg->getMessageType()));
            break;
    }
}

int main() {
    // 创建客户端
    auto client = ClientFactory::create("127.0.0.1", 8888);
    
    // 设置消息回调
    client->setMessageCallback(onServerMessage);
    
    // 设置连接回调
    client->setConnectionCallback([](const BaseConnection::ptr& conn) {
        LOG_INFO("Connected to server");
    });
    
    // 设置关闭回调
    client->setCloseCallback([](const BaseConnection::ptr& conn) {
        LOG_INFO("Disconnected from server");
    });
    
    // 连接服务器
    LOG_INFO("Connecting to server...");
    client->connect();
    
    // 等待连接建立
    std::this_thread::sleep_for(std::chrono::seconds(1));
    
    if (!client->connected()) {
        LOG_ERROR("Failed to connect to server");
        return -1;
    }
    
    // 测试RPC请求
    {
        auto req = MessageFactory::create<jsonrpc::RpcRequest>();
        req->setRid(UUIDUtil::generateUUID());
        req->setMessageType(MType::REQ_RPC);
        req->setMethod("add");
        
        Json::Value params;
        params["num1"] = 123;
        params["num2"] = 456;
        req->setParams(params);
        
        LOG_INFO("Sending RPC request...");
        client->send(req);
    }
    
    // 测试Topic请求
    {
        auto req = MessageFactory::create<jsonrpc::TopicRequest>();
        req->setRid(UUIDUtil::generateUUID());
        req->setMessageType(MType::REQ_TOPIC);
        req->setTopicKey("weather");
        req->setOptype(TopicOptype::TOPIC_PUBLISH);
        req->setTopicMsg("Today is sunny");
        
        LOG_INFO("Sending Topic request...");
        client->send(req);
    }
    
    // 测试Service请求
    {
        auto req = MessageFactory::create<jsonrpc::ServiceRequest>();
        req->setRid(UUIDUtil::generateUUID());
        req->setMessageType(MType::REQ_SERVICE);
        req->setMethod("weather_service");
        req->setOptype(ServiceOptype::SERVICE_DISCOVERY);
        
        LOG_INFO("Sending Service discovery request...");
        client->send(req);
    }
    
    // 等待响应
    std::this_thread::sleep_for(std::chrono::seconds(3));
    
    // 关闭连接
    client->shutdown();
    
    return 0;
}